import React, {PureComponent} from 'react';
import {Table,Input} from 'antd';

export default class  extends PureComponent {
  state = ({
    columns: [
      {
        title: '标题',
        key:'title',
        dataIndex: 'title',
        editable:true,
        render: (text, record, index)=>{
          if (record.editable){
            return (<Input onChange={e =>{ this.handleFieldChange(e, 'title', record.key)}} value={text}/>);
          }
        }
      },{
        title: '价格',
        key:'price',
        dataIndex: 'price',
        editable:true
      },{
        title: 'singlePrice',
        key:'singlePrice',
        dataIndex: 'singlePrice',
        editable:true
      },{
        title: '库存',
        key:'stock',
        dataIndex: 'stock',
        editable:true
      },
    ],
    data: [{'title': 'wanganshi','price':10,'singlePrice': 20, 'stock': 500,'editable':true}],
  });

  getRowByKey(key, newData) {
    return (newData || this.state.data).filter(item => item.key === key)[0];
  }

  handleFieldChange(e, fieldName, key) {
    const newData = this.state.data.map(item => {return { ...item }});
    console.info(newData || this.state.data);
    const target = this.getRowByKey(key, newData);
    if (target) {
      target[fieldName] = e.target.value;
      this.setState({ data: newData });
    }
  }
  render(){
    return (<Table dataSource={this.state.data} columns={this.state.columns}/>)
  }

}
